<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <!-- 缺陷描述 -->
      <el-form-item label="缺陷描述：" prop="defect_name" required>
        <el-input
          v-model="form.defect_name"
          type="textarea"
          :rows="3"
          placeholder="请输入缺陷描述"
          clearable
        />
      </el-form-item>

      <!-- 修改后的检测项类型下拉框 -->
      <el-form-item label="检测项类型：" prop="index_type" required>
        <el-select
          v-model="form.index_type"
          placeholder="请选择检测项类型"
          style="width: 100%"
          filterable
          :loading="typeLoading"
        >
          <el-option
            v-for="item in inspectionTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 缺陷等级 -->
      <el-form-item label="缺陷等级：" prop="defect_level" required>
        <el-select
          v-model="form.defect_level"
          placeholder="请选择缺陷等级"
          style="width: 100%"
        >
          <el-option
            v-for="item in defectLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 建议处理方法 -->
      <el-form-item label="建议处理方法：" prop="process_method" required>
        <el-input
          v-model="form.process_method"
          type="textarea"
          :rows="3"
          placeholder="请输入建议处理方法"
          clearable
        />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注：" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息（可选）"
          clearable
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">
        {{ isEditMode ? '保存修改' : '确 定' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

// 检测项类型映射关系
const INSPECTION_TYPE_MAP = {
  1: '外观',
  2: '视觉',
  3: '尺寸',
  4: '物理性能检测',
  5: '化学成分检测'
};

export default {
  name: 'CommonDefectsDialog',
  props: {
    visible: Boolean,
    title: String,
    formData: Object,
    isEditMode: {
      type: Boolean,
      default: false
    },
    defectLevelOptions: {
      type: Array,
      default: () => [
        { value: 'CR', label: '致命缺陷' },
        { value: 'MAJ', label: '严重缺陷' },
        { value: 'MIN', label: '轻微缺陷' }
      ]
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      typeLoading: false,
      form: {
        defect_id: null,
        defect_code: '',
        defect_name: '',
        index_type: '',
        defect_level: 'CR',
        process_method: '',
        remark: ''
      },
      rules: {
        defect_name: [
          { required: true, message: '请输入缺陷描述', trigger: 'blur' },
          { min: 5, max: 200, message: '长度在5到200个字符', trigger: 'blur' }
        ],
        index_type: [
          { required: true, message: '请选择检测项类型', trigger: 'change' }
        ],
        defect_level: [
          { required: true, message: '请选择缺陷等级', trigger: 'change' }
        ],
        process_method: [
          { required: true, message: '请输入建议处理方法', trigger: 'blur' },
          { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 300, message: '长度不能超过300个字符', trigger: 'blur' }
        ]
      },
      inspectionTypeOptions: []
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.resetForm()
        this.fetchInspectionTypes()
        if (this.isEditMode && this.formData) {
          this.form = {
            ...this.form,
            ...this.formData,
            // 确保数据类型正确
            defect_id: this.formData.defect_id ? Number(this.formData.defect_id) : null,
            index_type: this.formData.index_type ? Number(this.formData.index_type) : null
          }
        }
      }
    }
  },
  methods: {

    async generateDefectCode() {
      try {
        const response = await request({
          url: '/ldzl-basic/basic/numbers/auto/' + 5,
          method: 'get'
        })
        
        // 确保返回的是字符串类型
        if (response && response.msg) {
          this.form.defect_code = String(response.msg)
          alert(this.form.defect_code)
        } else if (response && response.data) {
          this.form.defect_code = String(response.data)
        } else {
          this.$message.error('生成编码失败：返回数据格式错误')
          return false
        }
        return true
      } catch (error) {
        console.error('生成编码失败:', error)
        this.$message.error('生成编码失败：' + (error.response?.data?.message || error.message))
        return false
      }
    },

    async fetchInspectionTypes() {
      try {
        this.typeLoading = true
        const response = await request({
          url: '/ldzl-qc/qc/defect/selectQcDefectType',
          method: 'post'
        })

        const responseData = response.data || response

        // 转换检测项类型数据，添加中文名称
        this.inspectionTypeOptions = (Array.isArray(responseData)
          ? responseData.map(item => {
              const value = item.index_type || item.value
              return {
                value: Number(value), // 确保value是数字类型
                label: INSPECTION_TYPE_MAP[value] || value
              }
            })
          : [])

        // 如果接口返回空数组，则使用本地映射数据
        if (this.inspectionTypeOptions.length === 0) {
          this.inspectionTypeOptions = Object.entries(INSPECTION_TYPE_MAP).map(([value, label]) => ({
            value: Number(value), // 确保value是数字类型
            label
          }))
        }
      } catch (error) {
        console.error('获取检测项类型失败:', error)
        // 如果接口请求失败，使用本地映射数据作为备选
        this.inspectionTypeOptions = Object.entries(INSPECTION_TYPE_MAP).map(([value, label]) => ({
          value: Number(value), // 确保value是数字类型
          label
        }))
      } finally {
        this.typeLoading = false
      }
    },

    resetForm() {
      this.form = {
        defect_id: null,
        defect_code: '',
        defect_name: '',
        index_type: '',
        defect_level: 'CR',
        process_method: '',
        remark: ''
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写完整必填信息')
          return
        }

        this.loading = true
        try {
          // 新增模式下自动生成编码
          if (!this.isEditMode) {
            const codeGenerated = await this.generateDefectCode()
            if (!codeGenerated) {
              this.loading = false
              return
            }
          }

          const payload = {
            defect_code: String(this.form.defect_code || ''),
            defect_name: String(this.form.defect_name || ''),
            index_type: this.form.index_type ? Number(this.form.index_type) : null,
            defect_level: String(this.form.defect_level || ''),
            process_method: String(this.form.process_method || ''),
            remark: this.form.remark ? String(this.form.remark) : null,
            create_by: 'system',
            create_time: new Date().toISOString()
          }

          const endpoint = this.isEditMode ? 'updateQcDefect' : 'insertQcDefect'

          if (this.isEditMode) {
            payload.defect_id = this.form.defect_id ? Number(this.form.defect_id) : null
            payload.update_by = 'system'
            payload.update_time = new Date().toISOString()
          }

          console.log('提交的数据:', payload)

          await request({
            url: `/ldzl-qc/qc/defect/${endpoint}`,
            method: 'post',
            data: payload
          })

          this.$message.success(this.isEditMode ? '修改成功' : '添加成功')
          this.$emit('submit-success')
          this.$emit('update:visible', false)
        } catch (error) {
          console.error('操作失败:', error)
          this.$message.error(error.response?.data?.message || '操作失败')
        } finally {
          this.loading = false
        }
      })
    },

    cancel() {
      this.$emit('update:visible', false)
      this.$emit('cancel')
    },

    handleClose(done) {
      if (JSON.stringify(this.form) !== JSON.stringify(this.initialForm)) {
        this.$confirm('未保存的数据将丢失，确定关闭吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.cancel()
          done()
        }).catch(() => {})
      } else {
        this.cancel()
        done()
      }
    }
  },
  created() {
    this.initialForm = JSON.parse(JSON.stringify(this.form))
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
